<template>
  <!-- 一键调价 -->
  <div>
    <el-dialog
      v-el-drag-dialog
      title="一键调价"
      :visible.sync="visible"
      width="1024px"
      @close="reset"
    >
      <div class="center">
        <!-- 描述列表 -->
        <el-form ref="form" class="form" :model="temp" label-position="right" label-width="80px">
          <el-form-item label="机构:">
            <el-tree-select
              v-model="temp.orgSNNo"
              :clearable="true"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择组织机构',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props:{
                  value:'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item label="价格分类:">
            <el-select v-model="query.priceCgId" clearable placeholder="请选择" @change="changePriceType" @clear="clearPrice">
              <el-option v-for="l in selectPriceList" :key="l.priceCgId" :value="l.priceCgId" :label="l.priceCgName" />
            </el-select>
          </el-form-item>
          <el-form-item label="报价类型:">
            <el-select v-model="temp.priceType" clearable placeholder="请选择">
              <el-option :value="1" label="下浮" />
              <el-option :value="2" label="固定" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类:" prop="orgSNNo">
            <el-tree-select
              v-model="shop.gtId"
              :clearable="true"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择商品分类',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                'expand-on-click-node': false,
                'highlight-current': true,
                props:{
                  value:'gtId',
                  label: 'gtName',
                  disabled: 'disabled',
                },
                data: goodsTreeDataCopy
              }"
              @node-click="selectGoodsTreeChange"
            />
          </el-form-item>
          <el-form-item label="商品名称:" class="merge-item">
            <el-select v-model="shop.goodsId" clearable>
              <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-circle-plus-outline" style="width: 70px; margin-left: 10px;" size="mini" @click="add">添加</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
        <div class="item">
          <el-form>
            <lb-table
              ref="lbTable"
              class="table"
              border
              highlight-current-row
              element-loading-text="加载中"
              :column="tableData.column"
              :data="tableData.data"
              :total="tableData.total"
              custom-column
              align="center"
            />
          </el-form>
        </div>
      </div>
      <!-- 底部 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save"> 开始调价 </el-button>
        <el-button @click="reset"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { defaultPaymentMethodMap } from '@/utils/map'
  import { queryPriceType, goodsTypeQueryList, priceCategoryList, queryPriceTypePriceOneKey } from '@/api'

  export default {
    name: 'adjustPrice',
    data() {
      return {
        visible: false,
        treeData: [],
        orgObj: {},
        goodsTreeData: [],
        goodsTreeDataCopy: [],
        goodsTypesDetailList: [],
        selectPriceList: [],
        shop: { gtId: null, goodsId: null },
        query: { priceCgId: null },
        defaultPaymentMethodMap,
        temp: {
          select: 1,
          gtTree: '',
          orgName: '', // 所属机构orgSNNo
          gtName: '',
          priceCgName: '',
          price: '',
          priceType: null,
          name: '',
          csmTypeSource: [0],
          code: '',
          roleType: '',
          dateType: 'createTime',
          date: [],
          csmType: 'csmPhone',
          csmText: '',
          time: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              width: 50
            },
            {
              prop: 'orgName',
              label: '机构'
            },
            {
              prop: 'priceCgName',
              label: '价格分类',
              width: 100
            },
            {
              prop: 'gtName',
              label: '商品类型',
              width: 100
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 150
            },
            {
              prop: 'priceType',
              label: '报价类型',
              width: 100,
              render: (h, { row }) => <span>{row.priceType === 1 ? '下浮' : row.priceType === 2 ? '固定' : '全部'}</span>
            },
            {
              prop: 'trend',
              label: '调整幅度',
              width: 80,
              render: (h, { row }) => <div style='display:flex;  justify-content: space-between'><i onClick={() => row.trend = 1} style={row.trend === 1 ? 'color:red;font-size:18px;cursor:pointer' : 'font-size:18px;cursor:pointer'} class='el-icon-top'>  </i><i onClick={() => row.trend = -1} style={row.trend === -1 ? 'color:red;font-size:18px;cursor:pointer' : 'font-size:18px;cursor:pointer'} class='el-icon-bottom'></i></div>
            },
            {
              prop: 'price',
              label: '调整金额（元）',
              width: 130,
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input size='mini' value={row[column.property]} onInput={(val) => { row[column.property] = val }}></el-input>
                  ) : (<span>{row[column.property]}</span>)}
                </div>
                )
              }
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 100,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    {row._edit ? (
                    <el-link size='mini' onClick={() => { this.handleSave(row) }}> 保存 </el-link>
                  ) : (
                    <el-link size='mini' onClick={() => { this.handleEdit(row) }}> 编辑 </el-link>)}
                    <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}> 删除 </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        },
        tagOptions: [
          {
            label: '家',
            value: '家'
          },
          {
            label: '公司',
            value: '公司'
          }
        ]
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await this.getTreeData()
      await this.$set(this.tableData, this.priceTypeMap)
      this.getGoodsTreeData()
    },
    mounted() {
      this.$watch('temp.orgSNNo', (val) => {
        // console.log(this.shop.gtId)
        if (!val) {
          this.query.priceCgId = ''
          this.selectPriceList = []
        }
      })
      this.$watch('shop.gtId', (val) => {
        // console.log(this.shop.gtId)
        if (!val) {
          this.shop.goodsId = ''
          this.goodsTypesDetailList = []
        }
      })
    },
    methods: {
      // 获取商品分类树
      async getGoodsTreeData() {
        const res = await goodsTypeQueryList({})
        // console.log(res)
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.goodsTreeData = getTreeData(data)
      },
      // 选择商品分类
      async selectGoodsTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        this.shop.goodsId = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          // const res = await goodsTypeDetail({ gtId: val })
          const params = {
            currentPage: 1,
            pageSize: 999,
            priceCgId: this.query.priceCgId,
            gtId: this.shop.gtId || 0,
            goodsId: this.shop.goodsId || 0
          }
          // console.log(this.goodsTreeData, 'goodsTreeData')
          const res1 = await priceCategoryList(params)
          // var data1 = res.data.rows
          var data2 = res1.data.rows
          if (data2.length) {
            this.goodsTypesDetailList = data2
          } else {
            this.goodsTypesDetailList = []
          }
        } catch (error) {
          console.log(error)
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async   selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
        this.orgObj = { ...value }
        this.query.priceCgId = null

        const params = {
          orgSNNo: value.orgSNNo,
          currentPage: 1,
          pageSize: 999
        }
        const res = await queryPriceType(params)
        this.selectPriceList = res.data.rows
      },
      clearPrice() {
        this.shop.gtId = ''
        this.goodsTreeDataCopy = []
        this.shop.goodsId = ''
        this.goodsTypesDetailList = []
      },
      // 价格分类变化筛选商品分类
      async changePriceType(val) {
        console.log(val)
        // priceCategoryList
        // this.shop.gtId = null
        // this.shop.goodsId = null
        const params = {
          currentPage: 1,
          pageSize: 999,
          priceCgId: val,
          gtId: this.shop.gtId || 0,
          goodsId: this.shop.goodsId || 0
        }
        // console.log(this.goodsTreeData, 'goodsTreeData')
        const res = await priceCategoryList(params)
        if (res.data.rows.length) {
          var list = res.data.rows
          var arr1 = list.map(l => l.gtId)
          var arr2 = [...new Set(arr1)]
          console.log(arr2)
          var arr3 = []
          arr2.forEach(l => {
            var obj = this.goodsTreeData.find(n => n.gtId === l)
            if (obj) {
              arr3.push(obj)
            }
          })
          console.log(arr3)
          this.goodsTreeDataCopy = arr3
        } else {
          this.goodsTreeDataCopy = []
        }
        console.log(val)
      },
      open(temp) {
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.type = 'edit'
          }
        })
      },
      // 添加
      add() {
        var org = this.orgObj
        if (!org.orgId) {
          this.$message.error('请选择机构')
          return
        }
        var priceCg = this.selectPriceList.find(l => l.priceCgId === this.query.priceCgId)

        // var priceCg = prcieObj
        if (!priceCg) {
          priceCg = {}
          priceCg.priceCgId = 0
          priceCg.priceCgName = '全部'
        }
        /* if(!priceCg || !priceCg.priceCgId) {
          this.$message.error("请选择价格分类");
            return;
        }*/
        // shop.gtId
        var goodsType = this.goodsTreeData.find(l => l.gtId === this.shop.gtId)
        if (!goodsType) {
          goodsType = { gtId: 0 }
        }
        if (!goodsType.gtId) {
          goodsType.gtName = '全部'
        }
        var goods = this.goodsTypesDetailList.find(l => l.goodsId === this.shop.goodsId)
        if (!goods) {
          goods = { goodsId: 0 }
        }
        if (goods.goodsId === 0) {
          goods.goodsName = '全部'
        }
        /* if(!goods || !goods.goodsId) {
          this.$message.error("请选择商品");
            return;
        }*/
        var priceType = this.temp.priceType
        if (!priceType) {
          priceType = -1
        }
        /* if(priceType.value == 0) {
          this.$message.error("请选择价格类型");
            return;
        }*/

        var rowData = {
          orgName: org.orgName,
          orgId: org.orgId,
          orgSNNo: org.orgSNNo,
          priceCgId: priceCg.priceCgId,
          priceCgName: priceCg.priceCgName,
          gtId: goodsType.gtId,
          gtName: goodsType.gtName,
          goodsId: goods.goodsId,
          goodsName: goods.goodsName,
          priceType: priceType,
          t: new Date().getTime(),
          trend: null,
          price: null
        }
        var exist = false
        var rows = this.tableData.data
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i]
          if (row.orgId === rowData.orgId && row.priceCgId === rowData.priceCgId &&
            row.gtId === rowData.gtId && row.goodsId === rowData.goodsId && row.priceType === rowData.priceType) {
            exist = true
            var index = i
            this.tableData.data[index] = rowData
            break
          }
        }
        if (!exist) {
          this.tableData.data.push(rowData)
        }
      },
      async save() {
        var rows = this.tableData.data
        // for (var i = 0; i < rows.length; i++) {
        //   var index = this.grid.datagrid('getRowIndex', rows[i])
        //   this.grid.datagrid('endEdit', index)
        // }
        // this.editRowIndex = null

        if (rows.length === 0) {
          this.$message.error('请添加调价内容')
          return
        }
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i]
          var index = i
          if (!row.trend) {
            this.$message.error(`第${index + 1}行 请选择调整幅度`)
            return
          }
          if (!row.price || row.price < 0) {
            this.$message.error(`第${index + 1}行 调整金额需大于0`)
            return
          }
          var reg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/
          if (!reg.test(row.price)) {
            this.$message.error(`第${index + 1}行 调整金额输入有误 请重新输入`)
            return
          }
        }
        const res = await queryPriceTypePriceOneKey(rows)
        if (res.success) {
          this.$message.success('调价成功')
          this.reset()
        }
        // $dlh.cmct.post({
        //   url: 'page/sys/price/define/priceCgDetail/onekey',
        //   contentType: 'application/json',
        //   data: JSON.stringify(rows)
        // }, function(rlt) {
        //   if (rlt.exc) {
        //     this.$message.error(rlt.exc)
        //     return
        //   }
        //   $dlh.toast.info('调价成功')
        //   $dlh.closeActiveWin()
        // })
      },
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
      },
      handleSave(row, $index) {
        this.$set(row, '_edit', false)
        this.$set(this.tableData.data, $index, JSON.parse(JSON.stringify(row)))
      },
      // 删除
      del(row, index) {
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.data.splice(index, 1)
          this.$message({
            type: 'success',
            message: '成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      reset() {
        this.temp = {
          select: 1,
          gtTree: '',
          orgName: '', // 所属机构orgSNNo
          gtName: '',
          priceCgName: '',
          price: '',
          priceType: null,
          name: '',
          csmTypeSource: [0],
          code: '',
          roleType: '',
          dateType: 'createTime',
          date: [],
          csmType: 'csmPhone',
          csmText: '',
          time: ''
        }
        this.$nextTick(() => {
          this.tableData.data = []
          this.shop = { gtId: null, goodsId: null }
          this.visible = false
        })
      }
    }
  }
</script>

<style lang='scss' scoped>
.center {
  height: 500px;
  font-size: 14px;
  font-weight: 400;
  color: #333;
  text-align: left;
  /deep/ .el-table__empty-block {
    width: auto !important;
  }
}

.item {
  margin-bottom: 30px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .title-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 6px;
      background: #01999f;
    }
    .title-text {
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      color: #01999f;
    }
  }
  &:last-child {
    margin-bottom: 0;
  }
  .content {
    margin-bottom: 30px;
  }
}

.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
